package com.example.demo.controller;

import com.example.demo.entity.*;
import com.example.demo.service.BookService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;
import java.io.UnsupportedEncodingException;
import java.util.*;

@RestController
@RequestMapping(value = "/book")
public class BookController {

    @Autowired
    private BookService bookService;

    private final int pageSize = 5;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @GetMapping(value = "/showAllBooks")
    public ApiResponse showAll(@RequestParam(value = "pn", defaultValue = "1") int pn) {
        PageHelper.startPage(pn, pageSize);
        List<Book> list = bookService.findAllBooks();
        PageInfo pageInfo = new PageInfo(list, pageSize);
        return new ApiResponse(StatusCodeMenu.SUCCESS, StatusMessageMenu.SUCCESS, pageInfo);
    }

    @GetMapping(value = "/borrowBookById/{bookid}")
    public ApiResponse borrowBookById(@PathVariable("bookid") String bookid,
                                      @RequestParam("username") String username) {
        Boolean isSuccess = bookService.borrowBookById(bookid, username);
        if (isSuccess == true) {
            //如果借书成功 总借书次数+1 利用redis存储
            int before = Integer.valueOf((String) stringRedisTemplate.opsForHash().get("countMap", username));
            stringRedisTemplate.opsForHash().put("countMap", username, String.valueOf(before + 1));
        }
        return new ApiResponse(StatusCodeMenu.SUCCESS, StatusMessageMenu.SUCCESS, isSuccess);
    }

    @GetMapping(value = "/returnBook/{bookid}")
    public ApiResponse returnBook(@PathVariable("bookid") String bookid,
                                  @RequestParam("username") String username) {
        Boolean isReturnSuccess = bookService.returnBook(bookid, username);

        return new ApiResponse(StatusCodeMenu.SUCCESS, StatusMessageMenu.SUCCESS, isReturnSuccess);

    }

    @GetMapping(value = "/showAllBooksBorrowed")
    public ApiResponse showAllBooksBorrowed(@RequestParam("username") String username) {
        String message = StatusMessageMenu.SUCCESS;
        Integer code = StatusCodeMenu.SUCCESS;
        List<Borrow> list = null;
        try {
            list = bookService.findAllBooksBorrowed(username);
            bookService.checkBookExpireStatus(list);
            for (Borrow borrow : list) {
                Date date = borrow.getExpiredate();
                date.setDate(date.getDate() + 1);
            }
        } catch (IndexOutOfBoundsException e) {
            message = StatusMessageMenu.NOT_FOUND;
            code = StatusCodeMenu.NOT_FOUND;
        }

        return new ApiResponse(code, message, list);
    }

    @GetMapping(value = "/showPopularBooks")
    public ApiResponse showAllPopularBooks(@RequestParam(value = "popularNum", defaultValue = "5") Integer popularNum) {
        List<PopularBook> list = bookService.findAllPopularBooks(popularNum);
        return new ApiResponse(StatusCodeMenu.SUCCESS, StatusMessageMenu.SUCCESS, list);
    }

    @GetMapping(value = "/showPopularUsers")
    public ApiResponse showPopularUserss(@RequestParam(value = "popularNum", defaultValue = "3") Integer popularNum) {
        Set<Object> countMap = stringRedisTemplate.opsForHash().keys("countMap");
        Iterator<Object> it = countMap.iterator();
        List<PopularUser> list = new ArrayList<>();
        int i = 0;
        while (it.hasNext()) {
            if (i == popularNum) {
                break;
            }
            String key = (String) it.next();
            String value = (String) stringRedisTemplate.opsForHash().get("countMap", key);
            list.add(new PopularUser(key, Integer.valueOf(value)));
            i++;
        }
        return new ApiResponse(StatusCodeMenu.SUCCESS, StatusMessageMenu.SUCCESS, list);
    }

    @GetMapping(value = "/searchBookByKeyword")
    public ApiResponse getBooksByKeyword(@RequestParam("keyword") String keyword,
                                         @RequestParam(value = "pn", defaultValue = "1") int pn,
                                         @RequestParam("searchType") String searchType
    ) throws UnsupportedEncodingException {
        PageHelper.startPage(pn, pageSize);
        Book book = new Book();
        if (searchType.equals("bookname")) {
            book.setBookname(searchType);
        } else if (searchType.equals("author")) {
            book.setAuthor(searchType);
        }
        List<Book> list = bookService.getBooksByKeyword(book, keyword);
        PageInfo pageInfo = new PageInfo(list, pageSize);
        return new ApiResponse(StatusCodeMenu.SUCCESS, StatusMessageMenu.SUCCESS, pageInfo);
    }

}
